package com.lagou.client;

import com.lagou.service.UserService;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ClientBootStrap {


    public static  final String parentNodeName="/dataSource";
    public final static String zkAddr = "127.0.0.1:2181";

    private static Map<String, String> configMap = new ConcurrentHashMap<>();

    public static ThreadLocal<ComboPooledDataSource> threadLocal = new ThreadLocal();

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = new ZkClient(zkAddr);

        boolean provider = zkClient.exists(parentNodeName);
        if (!provider) {
            return;
        }
        List<String> childrens = zkClient.getChildren(parentNodeName);
        if (childrens.size() == 0) {
            zkClient.createEphemeral(parentNodeName+"/driverClass","com.mysql.jdbc.Driver");
            zkClient.createEphemeral(parentNodeName+"/url","jdbc:mysql://192.168.179.1:3306/blog_system?serverTimezone=UTC");
            zkClient.createEphemeral(parentNodeName+"/username","root");
            zkClient.createEphemeral(parentNodeName+"/password","Test123-");
            setDataSource();
        }
        childrens = zkClient.getChildren(parentNodeName);
        for (String children : childrens) {
            String value = zkClient.readData(parentNodeName+"/" + children);
            configMap.put(children, value);
            zkClient.subscribeDataChanges(parentNodeName+"/" + children, new IZkDataListener() {
                @Override
                public void handleDataChange(String path, Object data) throws
                        Exception {
                    String key = path.replace(parentNodeName+"/", "");
                    configMap.put(key, (String)data);
                    if (threadLocal.get() != null) {
                        threadLocal.get().close();
                    }
                    setDataSource();
                }
                @Override
                public void handleDataDeleted(String s) throws Exception {
                    System.out.println(s+" 该节点被删除");
                }
            });
        }

        Connection connection = threadLocal.get().getConnection();
        System.out.println("connection:" + connection);

    }

    private void setDataSource() throws PropertyVetoException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(configMap.get("driverClass"));
        comboPooledDataSource.setJdbcUrl(configMap.get("url"));
        comboPooledDataSource.setUser(configMap.get("username"));
        comboPooledDataSource.setPassword(configMap.get("password"));
        threadLocal.set(comboPooledDataSource);
    }

}
